#!/usr/bin/python
import sys 
import os
import os.path
import subprocess
import codecs
import musicbrainz2.disc as mbdisc
import musicbrainzngs as mb
import utils

def get_release_ids(discid) :
	releases = mb.get_releases_by_discid(discid)
	releaseids = [r["id"] for r in releases["disc"]["release-list"]]
	return releaseids

def display_release_ids(releaseids) :
	n = len(releaseids)
	if n==0 :
		print "Disc is not yet in the MusicBrainz database."
		print "Consider adding it via", mbdisc.getSubmissionUrl(disc)
	else :
		print "Release ids found for discid=%s :" % discid
		for i, rid in enumerate(releaseids) :
			print "(%2d) %s" % (i, rid)
	return n

def cuefile_from_disc(disc) :
	yield u'FILE "dummy" WAVE'

	i = disc.getFirstTrackNum()
	for offset in disc.tracks:			
		r = offset[0] - 2*75
		ff = r % 75
		r = (r - ff)/75
		ss = r % 60
		r = (r - ss)/60
		mm = r 

		yield u'  TRACK %02d AUDIO' % i
		if i==1 and mm+ss+ff>0 :
				yield u'    INDEX 00 00:00:00'
		
		yield u'    INDEX 01 %02d:%02d:%02d' % (mm, ss, ff)
		
		i+=1
	yield u''


conn = utils.dbconn()

device = sys.argv[-1] if sys.argv else None
if device :
	disc = mbdisc.readDisc(device)
else :
	disc = mbdisc.readDisc()

	
discid = disc.getId()
print "discid :"
print discid
print "Submit to MusicBrainz at :"
print mbdisc.getSubmissionUrl(disc)

cuesheet = u"\n".join(cuefile_from_disc(disc))
print "#"*75
print cuesheet
print "#"*75

releaseids = get_release_ids(discid)
display_release_ids(releaseids)

## check if we have already ripped it
#cursor = conn.cursor()
#duplicates = list(cursor.execute("select release, num, path from disc where id=?",(discid,)))
#if len(duplicates)>0 :
#	print "!!!! This disc may be in the library already:"
#	for release, num, path in duplicates:
#		print "path=%s\nrelease=%s\ndiscnum=%d" % (path, release, num)
	
# we add "_" to the front of the directory because the first character
# of the discid can be ".", which hides the directory from squeezebox
discdir = os.path.join(os.path.abspath(utils.flacdir), "_"+discid)
print "create directory '%s' and read toc (y/N) ?" % discdir	
response = raw_input().lower() == "y"
if not response :
	sys.exit()
	
os.mkdir(discdir)
os.chdir(discdir)	

with open("toc","w") as f:
	pipe = subprocess.Popen(["wodim", "-toc"], stdout=subprocess.PIPE)
	f.write(pipe.stdout.read())
	
cuefile = os.path.join(discdir,"mbcue.out")
with codecs.open(cuefile,"w","utf-8") as f:
	f.write(cuesheet)

#with open(cuefile,"w") as f:
#	args = ["mkcue"]
#	if device :
#		args.append(device)
#	pipe = subprocess.Popen(args, stdout=subprocess.PIPE)
#	f.write(pipe.stdout.read())

# Can now start to read the audio track.
# this will do the trick:
###! screen -S rip -d -m <rip script> 

status = subprocess.check_call(["cdparanoia", "-l", "1-"])
if status :
	print "cdparanoia exited with code %d" % status
	sys.exit(status)
wavpath = os.path.join(discdir,"cdda.wav")

releaseid = None
while True :
	releaseids = get_release_ids(discid)
	display_release_ids(releaseids)
	if releaseids :
		print "Select the correct release (press enter for none) ..."
		response = raw_input()
		if response :
			choice = int(response)
			releaseid = releaseids[choice]
			break
	print "Check MusicBrainz again, now (Y/n) ?"
	if raw_input().lower().startswith("n") :
		break

if releaseid is None :
	print "No release found"
	sys.exit(1)

#print "registering release..."
#release = update_mbrelease(conn, releaseid)

releasediscnum = utils.get_discnum_in_release(releaseid, discid)
print "Disc is number #%d in release" % releasediscnum
	
print "Transcoding to FLAC"
status = utils.transcode_wav_to_flac(wavpath, cuefile, delete_src=True)
if status :
	sys.exit(status)
flacpath = os.path.join(discdir, "cdda.flac")

print "Tagging FLAC file..."
comments = utils.vorbis_comments_basic(releaseid, discid, releasediscnum)
print utils.set_flac_tags(flacpath, comments)

